'use client'
import React, { useEffect, useState, useRef } from 'react';
import './index.scss';
import { Spin, FloatButton, message, Image } from 'antd';
import { ChatMessage } from '../type';
import { OpenAIOutlined, LikeOutlined, DislikeOutlined, CopyOutlined, UpOutlined, DownOutlined, PlayCircleOutlined, PauseCircleOutlined } from '@ant-design/icons';
 
import { copyToClipboard } from '@/app/hook/copyToClipboard';
import keyStore from '@/app/store/key';
import Active from '@/app/store/active'
import Markdown from '@/app/components/MarkDown/page'


// 定义一个函数，用于清理代码
function cleanCode(code: string | null) {
    const regex = /^(?:\w+\d+)?\d*\s*/gm;
    return code?.replace(regex, '');
}

interface ChatcontentProps {
    chatlist: ChatMessage[];
    setData?: (value: any) => void
}

const Chatcontent: React.FC<ChatcontentProps> = ({ chatlist, setData }) => {
    const [chatList, setchatList] = useState<any>([])

    const { user, key, isdoc } = keyStore()
    const { audioActive, setaudioActive } = Active()

    // 停止播放
    const readerRef = useRef<ReadableStreamDefaultReader<Uint8Array> | null>(null);
    const isPlayingRef = useRef(false);
    const [isPlaying, setIsPlaying] = useState(false);
    const audioRef = useRef<HTMLAudioElement | null>(null);


    useEffect(() => {
        setchatList(chatlist)
    }, [chatlist]);


    // 桑智
    // const readtext = (text: string): { jsonPart: any; chat: string; textPart: string } => {
    //     try {
    //         let jsonPart: any = [];
    //         if (text.substring(0, 7) === '```json') {
    //             return { textPart: text, jsonPart: [], chat: '' };
    //         }
    //         if (text == '') {
    //             return { textPart: text, jsonPart: [], chat: '' };
    //         }
    //         const txt = text.split('<details style="color:gray;background-color: #f8f8f8;padding: 8px;border-radius: 4px;" open> <summary> Thinking... </summary>')[1]
    //         const newtext = txt.split('</details>');
    //         if (text.indexOf('</details>') === -1) {
    //             return { jsonPart, chat: newtext[0], textPart: '' };
    //         }
    //         const parts = text.split('</details>');
    //         if (parts.length === 1) {
    //             return { jsonPart, chat: newtext[0], textPart: '' };
    //         } else if (parts.length === 2) {
    //             return { jsonPart, chat: newtext[0], textPart: parts[1] };
    //         } else {
    //             return { jsonPart, chat: newtext[0], textPart: parts.slice(1).join('</details>') };
    //         }
    //     } catch {
    //         return { jsonPart: [], chat: '', textPart: '' };
    //     }
    // };


    // 新建
    const readtext = (text: string): { jsonPart: any; chat: string; textPart: string } => {
        if (isdoc || text === '' || text.substring(0, 7) === '```json') {
            return { textPart: text, jsonPart: [], chat: '' };
        }
        try {
            const detailsEndIndex = text.indexOf('</details>');
            if (detailsEndIndex === -1) {
                return { jsonPart: [], chat: text, textPart: '' };
            }
            const chat = text.substring(0, detailsEndIndex);
            const textPart = text.substring(detailsEndIndex + '</details>'.length);
            return { jsonPart: [], chat, textPart };
        } catch (error) {
            console.error('Error in readtext function:', error);
            return { jsonPart: [], chat: '', textPart: '' };
        }
    };

    useEffect(() => {
        if (!isPlaying) {
            stopAudio(); // 确保停止播放和取消流式请求
        }

    }, [isPlaying]);

    const stopAudio = () => {
        setaudioActive(-1)
        isPlayingRef.current = false;
        setIsPlaying(false);
        if (readerRef.current) {
            readerRef.current.cancel().then(() => {
                readerRef.current = null;
            }).catch(error => {
                console.error('终止流式请求失败', error);
            });
        }
        if (audioRef.current) {
            audioRef.current.pause();
        }
    };

    const getAudio = async (id: string, text: string, index: number) => {
        try {
            text = text.replace(/!\(([^)]+)\)/g, '').trim();
            if (isPlayingRef.current) {
                message.error('请先停止播放');
                return;
            }
            setaudioActive(index);
            const data = { text, user };
            const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL_ALIAS}/text-to-audio`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer app-J4ozWYK7UJv1FAOIJiniP30X'
                },
                body: JSON.stringify(data)
            });

            // 检查响应状态
            if (!response.ok) {
                const errorData = await response.json();
                console.error('Client error:', errorData.message);
                message.error('该Agent暂不支持语音播报');
                return;
            }

            // 创建MediaSource和Audio元素
            const mediaSource = new MediaSource();
            const audioElement = new Audio();
            audioRef.current = audioElement;
            audioElement.src = URL.createObjectURL(mediaSource);

            // 监听MediaSource打开事件
            mediaSource.onsourceopen = () => {
                const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');
                let isUpdating = false;

                // 读取和追加音频块
                function appendChunks() {
                    if (isUpdating || !isPlayingRef.current) return;
                    isUpdating = true;
                    if (!readerRef.current) return
                    readerRef.current.read().then(({ done, value }) => {
                        if (done || !isPlayingRef.current) {
                            if (mediaSource.readyState === 'open') {
                                mediaSource.endOfStream();
                            }
                            return;
                        }
                        sourceBuffer.appendBuffer(value);
                        sourceBuffer.onupdateend = () => {
                            isUpdating = false;
                            if (mediaSource.readyState === 'open' && done) {
                                mediaSource.endOfStream();
                            }
                            appendChunks();
                        };
                    }).catch(error => {
                        console.error('读取流数据失败', error);
                        if (mediaSource.readyState === 'open') {
                            mediaSource.endOfStream();
                        }
                    });
                }

                // 设置readerRef用于读取响应体
                if (!response.body) return
                const reader = response.body.getReader();
                readerRef.current = reader;

                // 开始追加音频块
                isPlayingRef.current = true;
                setIsPlaying(true);
                appendChunks();
            };

            // 监听MediaSource错误事件
            mediaSource.addEventListener('sourceerror', (error) => {
                console.error('MediaSource 错误', error);
                if (mediaSource.readyState === 'open') {
                    mediaSource.endOfStream();
                }
            });

            audioElement.onended = () => {
                isPlayingRef.current = false;
                setIsPlaying(false);
                URL.revokeObjectURL(audioElement.src);
            };

            audioElement.onerror = (error) => {
                if (mediaSource.readyState === 'open') {
                    mediaSource.endOfStream();
                }
            };
            await audioElement.play();
        } catch (error) {
            console.error('音频播放失败', error);
        }
    };

    const [web, setweb] = useState(1)

    return (
        <div className='chatcontent'>
            {
                chatList.map((item: any, index: number) => {
                    const { textPart, chat } = readtext(item.answer);
                    return <div key={item.id} className='allagent'>
                        <div className='agentContentItem agentright'>
                            <div className='agentContentTxt' style={{ backgroundColor: '#eff6ff' }}>
                                {item.query}
                            </div>
                        </div>

                        <div className='agent_img'>
                            <Image.PreviewGroup >
                                {
                                    item['file_img_list'] && item['file_img_list'].map((item: any, index: number) => {
                                        return <div key={index}>
                                            {
                                                item.thumbUrl ? <Image width={150} src={item.thumbUrl} /> : <div className='word'>
                                                    <img src="/file.svg" alt="" />
                                                    <div className='wordname'>
                                                        {item.name}
                                                    </div>
                                                </div>
                                            }
                                        </div>
                                    })
                                }
                            </Image.PreviewGroup>
                        </div>

                        <div className='agentContentItem agentleft'>
                            <img src='/logo.svg' alt="" />
                            <div className='agentContentTxt'>
                                {
                                    item.answer == '' ? <Spin /> : <>
                                        {
                                            isdoc ? null : <div className='reasoningbutton' onClick={(e) => {
                                                e.stopPropagation()
                                                if (item['flag'] == undefined) {
                                                    item['flag'] = true
                                                } else {
                                                    item['flag'] = !item['flag']
                                                }
                                                setweb(web + 1)
                                            }}><OpenAIOutlined />已深度思考
                                                {!item['flag'] ? <DownOutlined /> : <UpOutlined />}
                                            </div>
                                        }

                                        {
                                            item['flag'] == undefined ? <div className='reasoning'>
                                                {chat}
                                            </div> : item['flag'] ? <div className='reasoning'>
                                                {chat}
                                            </div> : ''
                                        }
                                        <Markdown content={textPart} />
                                    </>
                                }
                                {
                                    item['prompt'] != undefined && item.status == 'normal' && <div className='prompt'>
                                        {
                                            item['prompt'].map((item: any, index: number) => {
                                                return <div className='promptitem' key={index} onClick={(e) => {
                                                    e?.stopPropagation()
                                                    setData?.(item)
                                                }}>
                                                    {item}
                                                </div>
                                            })
                                        }
                                    </div>
                                }
                                {
                                    item.answer != '' && item.status == 'normal' && <div className='message_icon'>
                                        <LikeOutlined className="icon like" style={{ color: item.feedback == null ? '' : (item.feedback['rating'] == 'like' ? 'green' : '') }} />
                                        <DislikeOutlined className="icon dislike" style={{ color: item.feedback == null ? '' : (item.feedback['rating'] == 'dislike' ? 'red' : '') }} />
                                        <CopyOutlined onClick={() => {
                                            message.success('复制成功')
                                            copyToClipboard(cleanCode(textPart) || '')
                                        }} />
                                        {
                                            audioActive == index ?
                                                <PauseCircleOutlined onClick={() => stopAudio()} /> :
                                                <PlayCircleOutlined onClick={() => { getAudio(item.id, textPart, index) }} />
                                        }
                                    </div>
                                }

                            </div>
                        </div>
                    </div>
                })}
            <FloatButton.BackTop />
        </div >
    );
}

export default Chatcontent